package cn.gxufe.reliable.message.api.producer.impl;

import cn.gxufe.reliable.message.api.common.BaseTryService;
import cn.gxufe.reliable.message.api.producer.TryServiceProducer;
import cn.gxufe.reliable.message.common.Message;
import cn.gxufe.reliable.message.common.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yingjie.rong
 **/
public class TryServiceProducerImpl extends BaseTryService implements TryServiceProducer {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public ResultVo tryConfirm(Long messageId, String key, String header) {
        int anInt =  getStatus(messageId,key,header,Message.SOURCE_SERVICE_KEY_PREFIX);
        try {
            if( Message.STATUS_PREPARE == anInt){
                List<Object[]> list = new ArrayList<>();
                list.add(new Object[]{ Message.STATUS_CONFIRM, messageId, Message.STATUS_PREPARE ,Message.SOURCE_SERVICE_KEY_PREFIX+key });
                jdbcTemplate.batchUpdate( "update reliable_message set status=? , id = ? where  status = ?  AND `key` = ?",list );
                return ResultVo.ok();
            }else if( Message.STATUS_CONFIRM == anInt  ){
                return ResultVo.ok();
            } else {
                return ResultVo.error(Message.RESPONSE_CODE_NOT_FOUNT,"not found");
            }
        }catch (Exception e){
            return ResultVo.error(e.getMessage());
        }
    }

}
